/*!
 * ngChat
 * v0.1.1-alpha
 * Copyright 2015 Lixuecai Co. http://lixuecai.com/
 * See LICENSE in this repository for license information
 */
chatfriendxxx=null;
(function(){

	angular.module('ngChat', [
		'ngChat.plugins'
	]);

	angular.module('ngChat.plugins', [])

		.factory('$cordovaChat', ['$q', '$window', '$rootScope', '$timeout', '$http', function ($q, $window, $rootScope, $timeout, $http) {

			var BOSH_SERVICE = '';//'http://192.168.0.117:5280/http-bind';
			var chaturi='';//'LXC-PC'
			var chatuser = '';//'1001';
			var chatuserp = '';//'123';
			var chatretime = 5;//'123';
			var chatconnection = null;
			var litedb = null;
			var chatdisconnectionreason = "";
			var sqlchatcreate = "CREATE TABLE IF NOT EXISTS chatmsg{0} (id integer primary key, msg text, fromuser integer,touser integer,msgtype integer,msglength integer,add_time char(19))";
			var sqlchatinsert = "INSERT INTO chatmsg{0} (msg, fromuser, touser, add_time,msgtype,msglength) VALUES ('{1}',{2},{3},'{4}',{5},{6})";
			var sqlchatselect = "select id, msg, fromuser, touser, add_time,msgtype,msglength from chatmsg{0} {1}";
			var sqlfriendcreate = "CREATE TABLE IF NOT EXISTS chatfriend{0} (id integer primary key, msg text, " +
				"fromuser integer,fromname text,fromimg text,fromnew integer,add_time char(19),fromtype integer,UNIQUE(fromuser));";
			var sqlfriendinsert = "INSERT or replace INTO chatfriend{0} (msg, fromuser, fromname, fromimg, fromnew, add_time,fromtype,gender) VALUES ('{1}',{2},'{3}','{4}',{5},'{6}','{7}','{8}')";
			var sqlfriendupdate = "update chatfriend{0} set msg='{1}', fromuser={2}, fromname='{3}', fromimg='{4}', fromnew='{5}', add_time='{6}',fromtype='{7}' where {8}";
			var sqlfriendselect = "select id, msg, fromuser, fromname, fromimg, fromnew, add_time,fromtype,gender from chatfriend{0} {1}";
			var sqlfrienddelete = "delete from chatfriend{0} {1}";
			var sqlfriendnew = "update chatfriend{0} set fromnew=0 where fromuser={1}";
			var sqlfriendmaster = "select sql from sqlite_master where tbl_name='chatfriend{0}' and type='table'";
			var sqlfriendaddgender = "ALTER TABLE chatfriend{0} ADD gender integer";
			function ChatOpenDatabase(){
				if(window.sqlitePlugin){
					//litedb = window.sqlitePlugin.openDatabase({name: "chat.db"});
					return true;
				}
				return false;
			}
			function ChatCloseDatabase(){
				if(!!litedb){
					//litedb.close();
					litedb=null;
					return true;
				}
				return false;
			}
			function ChatCheckNetWork(){
				var chatcheckurl = SITE_URL+ "chat.php?callback=JSON_CALLBACK";
				$http.jsonp(chatcheckurl,{timeout:2000,cache:false}).success(function() {
					strophelog('ChatCheckNetWork success');
					checkflag=false;
					chatconnect();
				}).error(function() {
					strophelog('ChatCheckNetWork error');
					$timeout(function(){
						ChatCheckNetWork();
					},3000);
				});
			}
			var checkflag=false;
			function onChatConnect(status)
			{
				strophelog('onChatConnect status='+status);
				if (status == Strophe.Status.CONNECTING) {
					strophelog('onChatConnect Strophe.Status.CONNECTING.');
				} else if (status == Strophe.Status.CONNFAIL) {
					strophelog('onChatConnect Strophe.Status.CONNFAIL connect.chatdisconnectionreason='+chatdisconnectionreason);
					if(chatdisconnectionreason==""){
						$timeout(function(){
							//ChatCheckNetWork();
							strophelog('重新连接消息服务器  Strophe.Status.CONNFAIL');
							//chatconnection.receipts.addReceiptHandler(onChatMessage);
							chatconnection.addHandler(onChatMessage, null, 'message', 'chat',null,null);
							chatconnection.connect(chatuser+'@'+chaturi,chatuserp,onChatConnect,chatretime);
						},3000);
					}
				} else if (status == Strophe.Status.DISCONNECTING) {
					strophelog('onChatConnect Strophe.Status.DISCONNECTING.');
				} else if (status == Strophe.Status.DISCONNECTED) {
					strophelog('onChatConnect Strophe.Status.DISCONNECTED connect.chatdisconnectionreason='+chatdisconnectionreason);
					if(chatdisconnectionreason==""){
						$timeout(function(){
							//ChatCheckNetWork();
							strophelog('重新连接消息服务器 Strophe.Status.DISCONNECTED');
							//chatconnection.receipts.addReceiptHandler(onChatMessage);
							chatconnection.addHandler(onChatMessage, null, 'message', 'chat',null,null);
							chatconnection.connect(chatuser+'@'+chaturi,chatuserp,onChatConnect,chatretime);
						},1000);
					}
				} else if (status == Strophe.Status.CONNECTED) {
					strophelog('onChatConnect Strophe.Status.CONNECTED.');


					if(window.sqlitePlugin){
						if(ChatOpenDatabase()){
							// litedb.executeSql('DROP TABLE IF EXISTS
							// chatmsg{0}'.format(chatuser));
							//litedb.executeSql(sqlchatcreate.format(chatuser),null);
							//litedb.executeSql(sqlfriendcreate.format(chatuser),null);
							ChatCloseDatabase();
						}
					}
					chatconnection.send($pres().tree());
				}
			}
			function pinghandler(handler){
				console.log('pinghandler',handler);
			}
			function strophelog(logs){
				//console.log('消息处理日志',logs);
				//if(typeof logs=='string')
				//showtoast(logs);
			}
			function onChatXmlInput(data){
				strophelog('onChatXmlInput');
				strophelog(data);
			}

			function onChatXmlOutput(data){
				strophelog('onChatXmlOutput');
				strophelog(data);
			}

			function onChatRawInput(data){
				strophelog('onChatRawInput');
				strophelog(data);
			}

			function onChatRawOutput(data){
				strophelog('onChatRawOutput');
				strophelog(data);
			}
			function onChatMessage(data){
				try{
					strophelog('新消息 onChatMessage');
					//strophelog(data);
					if(data.nodeName=='message'&&data.getAttribute('type')=='chat'){
						ChatMessageToLite(data);
					}
					else{
						for(mi=0;mi<data.childElementCount;mi++){
							if(data.childNodes[mi].nodeName=='message'&&data.childNodes[mi].getAttribute('type')=='chat') {
								ChatMessageToLite(data.childNodes[mi]);
							}
						}
					}
				}
				catch(e){
					strophelog('onChatMessage process message error')
					strophelog(e);
				}
				return true;
			}
			function onChatError(data){
				try{
					strophelog('onChatError');
					strophelog(data);
				}
				catch(e){
					strophelog('onChatError process message error')
					strophelog(e);
				}
				return true;
			}
			function chatconnect() {
				//var q = $q.defer();
				try{
					strophelog('ChatConnect function');
					if(BOSH_SERVICE==''){
						//q.reject('no service url');
					}
					else{
						/*
						 if(chatconnection!=null&&chatconnection.conncted){
						 strophelog('ChatConnect chatconnection.disconnect');
						 chatdisconnectionreason = "ChatConnect";
						 chatconnection.disconnect(chatdisconnectionreason);
						 }*/
						if(chatuser==null||chatuser==''){
							//q.reject('no chat user');
						}
						else{
							//alert('chatdisconnectionreason3');
							chatdisconnectionreason = "";
							Strophe.log = function (level, msg) {
								//console.log('Strophe.log ',level,msg);
								//showtoast(msg);
							};
							chatconnection = new Strophe.Connection(BOSH_SERVICE, {'keepalive': true,sync: false});
							//chatconnection.addHandler(onChatError, null, 'message', 'error',null,null);
							//chatconnection.receipts.addReceiptHandler(onChatMessage);
							chatconnection.addHandler(onChatMessage, null, 'message', 'chat',null,null);
							chatconnection.connect(chatuser+'@'+chaturi,chatuserp,onChatConnect,chatretime);
							//chatconnection.rawInput = onChatRawInput;
							//chatconnection.rawOutput = onChatRawOutput;
							//chatconnection.xmlInput = onChatXmlInput;
							//chatconnection.xmlOutput = onChatXmlOutput;
							//q.resolve(true);
						}
					}
				}
				catch(e){
					strophelog('ChatConnect function process error');
					strophelog(e);
				}
				//return q.promise;
			}
			function ChatMessageToLite(data){
				strophelog("ChatMessageToLite");
				if(data.getAttribute('to')==chatuser+'@'+chaturi && data.getAttribute('type')=='chat')// 1002@LXC-PC
				{
					msg = data.childNodes[0].childNodes[0].nodeValue;
					fromid = data.getAttribute('from').split('@')[0];
					fromname = data.getAttribute('fromname');
					fromimg = data.getAttribute('fromimg');
					fromtype = data.getAttribute('fromtype');
					msgtype = data.getAttribute('msgtype');
					msglength = data.getAttribute('msglength');
					to = data.getAttribute('to').split('@')[0];
					gender=data.getAttribute('gender');
					genderto=data.getAttribute('genderto');
					cid=data.getAttribute('cid');
					ChatWriteLite(to,msg,fromid,fromname,fromimg,fromtype, null,null,msgtype,msglength,gender,genderto,cid);
				}
			}
			function ChatWriteLite(to,msg,fromid,fromname,fromimg,fromtype, toname,toimage,msgtype,msglength,gender,genderto,cid){
				console.log('数据啊',cid);
				strophelog("ChatWriteLite write lite");
				msgdate = new Date();
				msgd=msgdate.getFullYear()+"/"+(msgdate.getMonth()+1)+"/"+msgdate.getDate()+' '+msgdate.getHours()+':'+msgdate.getMinutes()+':'+msgdate.getSeconds();
				strophelog(msg+' from '+fromid+' to '+to+' '+msgd);
				insertid = 0;

				var fromnew=1;
				if(ChatOpenDatabase()){
					if(msgtype<100&&window.device){
						/*litedb.executeSql(sqlchatinsert.format(chatuser,msg,fromid,to,msgd,msgtype,msglength),null,function(res){
						 strophelog('ChatWriteLite sqlchatinsert');
						 insertid=res.insertId

						 });*/
					}
					fromto = 0;
					if(msgtype==1){
						friendmsg='[语音]'
					}
					else if(msgtype==2){
						friendmsg='[图片]'
					}
					else{
						friendmsg=msg;
					}
					if(msgtype<100){
						if(chatuser==to){
							fromto=fromid;
							//strophelog(sqlfrienddelete.format(chatuser," where fromuser="+fromto));


							//strophelog(res);
							//if(res.rows.length==0){
							if(window.device){
								/*litedb.transaction(function(tx) {
								 strophelog(sqlfriendselect.format(chatuser," where fromuser="+fromto));
								 tx.executeSql(sqlfriendselect.format(chatuser," where fromuser="+fromto),null,function(tx, res){
								 strophelog(sqlfriendselect.format(chatuser," where fromuser="+fromto));
								 strophelog('历史记录',res);
								 if(res.rows!=undefined&&res.rows.length>0){
								 fromnew = parseInt(res.rows.item(0).fromnew)+1;
								 }
								 strophelog(sqlfriendinsert.format(chatuser,friendmsg,fromto,fromname,fromimg,fromnew,msgd,fromtype,gender))
								 tx.executeSql(sqlfriendinsert.format(chatuser,friendmsg,fromto,fromname,fromimg,fromnew,msgd,fromtype,gender),null,function(tx, res){});
								 });
								 }, function(error) {
								 strophelog('transaction error: ' + error.message);
								 }, function() {
								 strophelog('transaction ok');
								 });*/
							}
							//}
							/*else{
							 fromnew = parseInt(res.rows.item(0).fromnew)+1;
							 strophelog(sqlfriendupdate.format(chatuser,friendmsg,fromto,fromname,fromimg,fromnew,msgd,fromtype," fromuser="+fromto));
							 litedb.executeSql(sqlfriendupdate.format(chatuser,friendmsg,fromto,fromname,fromimg,fromnew,msgd,fromtype," fromuser="+fromto),null,function(res){
							 strophelog('sqlfriendupdate');
							 strophelog(res);
							 });
							 }*/

						}
						else{
							fromto=to;
							//strophelog(sqlfriendselect.format(chatuser," where fromuser="+fromto));

							//strophelog(res);
							//if(res.rows.length==0){
							if(window.device){
								/*litedb.transaction(function(tx) {
								 strophelog(sqlfriendselect.format(chatuser," where fromuser="+fromto));
								 tx.executeSql(sqlfriendselect.format(chatuser," where fromuser="+fromto),null,function(tx, res){
								 strophelog(sqlfriendselect.format(chatuser," where fromuser="+fromto));
								 strophelog('历史记录',res);
								 if(res.rows!=undefined&&res.rows.length>0){
								 fromnew = parseInt(res.rows.item(0).fromnew);
								 }

								 strophelog(sqlfriendinsert.format(chatuser,friendmsg,fromto,fromname,fromimg,fromnew,msgd,fromtype,genderto))
								 tx.executeSql(sqlfriendinsert.format(chatuser,friendmsg,fromto,toname,toimage,fromnew,msgd,fromtype,genderto),null,function(tx, res){});
								 });
								 }, function(error) {
								 strophelog('transaction error: ' + error.message);
								 }, function() {
								 strophelog('transaction ok');
								 });*/
							}
							//}
							/*else{
							 fromnew = 0;
							 strophelog(sqlfriendupdate.format(chatuser,friendmsg,fromto,toname,toimage,fromnew,msgd,fromtype," fromuser="+fromto));
							 litedb.executeSql(sqlfriendupdate.format(chatuser,friendmsg,fromto,toname,toimage,fromnew,msgd,fromtype," fromuser="+fromto),null,function(res){
							 strophelog('sqlfriendupdate');
							 strophelog(res);
							 });
							 //}*/

						}
					}
					ChatCloseDatabase();
					// 读取数据
					/*
					 * litedb.executeSql(sqlchatselect.format(chatuser,"1=1"),null,function(res){
					 * strophelog('res'); //res.rows.item(1).id strophelog(res);
					 * },function(err){ strophelog('err'); strophelog(err); });
					 */
				}
				// 主键，消息内容，发送者，接收者，发送时间
				chatmsg={
					id : insertid,
					msg: msg,
					fromuser : fromid,
					fromname: fromname,
					fromimg: fromimg,
					toimage:toimage,
					toname:toname,
					fromtype:fromtype,
					touser : to,
					add_time : msgd,
					msgtype: msgtype,
					msglength: msglength,
					chatuser:chatuser,
					fromnew:fromnew,
					gender:gender,
					genderto:genderto,
					cid:cid
				};


				if(msgtype<100){
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveNewEvent', chatmsg);
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveEvent', chatmsg);
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveShowEvent', chatmsg);
				}else if(msgtype==100){
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveCdEvent', chatmsg);
				}else if(msgtype==101){
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveNewFEvent', chatmsg);
				}else if(msgtype==102){
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveAddFEvent', chatmsg);
				}else{
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveOrtherEvent', chatmsg);
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveOrtherEventUser', chatmsg);
					$rootScope.$broadcast('$cordovaChat:ChatMessageReciveOrtherEventTutor', chatmsg);
				}
			}
			//执行sql，成功function,失败function
			function ChatExecuteSql(sql,success,error){
				if(ChatOpenDatabase()){
					if(window.device){
						/*litedb.executeSql(sqlchatselect.format(chatuser,"1=1"),null,function(res){
						 if (typeof success !== "function") {
						 throw "success expected a function";
						 }
						 success(res);
						 },function(err){
						 if (typeof error !== "function") {
						 return;
						 }
						 error(err);
						 });*/
					}
				}
			}

			return {
				init: function (url,uri,user,p) {
					//var q = $q.defer();
					BOSH_SERVICE=url;
					chaturi=uri;
					chatuser=user;
					chatuserp=p;
					//q.resolve();
					//return q.promise;
				},

				ChatConnect: function () {
					chatconnect();
				},

				GetChatConnect: function () {
					return chatconnection;
				},

				ChatConnected: function(){
					if(chatconnection!=null&&chatconnection.connected){
						return chatconnection.connected;
					}
					return false;
				},

				ChatDisConnect: function(){
					var q = $q.defer();
					try{
						strophelog('ChatDisConnect logout');
						chatdisconnectionreason = "logout";
						chatconnection.disconnect(chatdisconnectionreason);
						$rootScope.$$listeners['$cordovaChat:ChatMessageReciveEvent'] = [];
						$rootScope.$$listeners['$cordovaChat:ChatMessageReciveShowEvent'] = [];
						$rootScope.$$listeners['$cordovaChat:ChatMessageReciveCdEvent'] = [];
						chatuser=null;
						chatuserp=null;
						q.resolve(true);
					}
					catch(e){
						q.reject(e.message);
					}
					return q.promise;
				},

				ChatSendMessage: function (to, body, fromname, fromimg, fromtype, toname,toimage,msgtype,msglength,gender,genderto,cid) {
					var q = $q.defer();
					try{
						//strophelog('chatconnection.connected');
						//strophelog(chatconnection.connected);
						//strophelog(to);strophelog( body);strophelog(fromname);strophelog(fromimg);strophelog(fromtype);strophelog(toname);strophelog(toimage);
						if(!chatconnection.connected)
						{
							q.reject('未连接到消息服务器');
						}
						else{
							var msg = $msg({to: to+'@'+chaturi, type: 'chat',fromname:fromname,fromimg:fromimg,fromtype:fromtype,msgtype:msgtype,msglength:msglength,gender:gender,genderto:genderto,cid:cid});
							// msg.attrs('fromname',fromname).attrs('fromimg',fromimg);
							if (body) {
								msg.c('body', {}, body);
							}
							else{
								q.reject('no body');
							}
							if(!chatconnection.connected)
								q.reject('未连接到消息服务器');
							else{
								chatconnection.send(msg.tree());
								ChatWriteLite(to,body,chatuser,fromname,fromimg,fromtype, toname,toimage,msgtype,msglength,gender,genderto,cid)
								q.resolve(true);
							}
						}
					}
					catch(e){
						q.reject(e.message);
					}
					return q.promise;
				},

				// 执行sql
				ChatSqlExecute: function (sql){
					var q = $q.defer();
					try{
						strophelog(sql);
						if(ChatOpenDatabase()){
							if(window.device){
								/*litedb.executeSql(sql,null,function(res){
								 strophelog(res);
								 q.resolve(res);
								 },function(err){
								 strophelog(err);
								 q.reject(err);
								 });*/
								//ChatCloseDatabase();
							}
							else{
								q.reject("open db error");
							}
						}
					}
					catch(e){
						q.reject(e.message);
					}
					return q.promise;
				},

				ChatFriendClearNew: function (fromid){
					var q = $q.defer();
					try{
						if(ChatOpenDatabase()){
							strophelog(sqlfriendnew.format(chatuser,fromid));
							if(window.device){
								/*litedb.executeSql(sqlfriendnew.format(chatuser,fromid),null,function(res){
								 q.resolve(res);
								 },function(err){
								 q.reject(err);
								 });*/
							}
							//ChatCloseDatabase();
						}
					}
					catch(e){
						q.reject(e.message);
					}
					return q.promise;
				},

				sqlchat: function(){
					return sqlchatselect.format(chatuser,"");
				},

				sqlfriend: function(){
					return sqlfriendselect.format(chatuser,"");
				},
				sqlfriendmaster:function(){
					return sqlfriendmaster.format(chatuser);
				},
				sqlfriendaddgender:function(){
					return sqlfriendaddgender.format(chatuser);
				}
			};
		}]);
})();